/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package yandexfotkibackup;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.ToolBar;
import javafx.scene.control.cell.ProgressBarTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.Callback;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;

/**
 *
 * @author petr
 */
public class YandexFotkiBackup extends Application implements GuiEventsManager {

    private TableView tableView;
    private String userName;
    private Stage stage;
    private ThreadManager threadManager;

    private void init(Stage primaryStage) throws MalformedURLException, IOException {
        stage = primaryStage;
        threadManager = new ThreadManager();
        goToLogin();
    }

    @Override
    public void start(Stage primaryStage) throws MalformedURLException, IOException {
        init(primaryStage);
        primaryStage.show();
    }

    private HBox getUserNameBox() {
        Label label = new Label("Enter the user name:");
        TextField tb = new TextField("norom");
        Button button = new Button("Find");
        button.setOnAction(new EventHandlerImpl(tb, this));
        tb.setMaxWidth(Double.MAX_VALUE);
        //HBox with spacing = 5
        HBox hbox = new HBox(5);
        hbox.getChildren().addAll(label, tb, button);
        hbox.setAlignment(Pos.CENTER_LEFT);
        return hbox;
    }

    /**
     * @return the userName
     */
    public String getUserName() {
        return userName;
    }

    /**
     * @param userName the userName to set
     */
    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Override
    public void onDownloadAlbom(AlbomInfo albom) {
        //TODO onDownloadAlbom(AlbomInfo albom) 
        //TODO fork new procces
        String url = "http://api-fotki.yandex.ru/api/users/" + userName + "/album/" + albom.getId() + "/photos/";
//        System.out.println("Download" + albom);
//        URLConnection conn;
//       
//        try {
//            conn = new URL(url).openConnection();
//            //читаем то, что отдал нам сервер
//            String html = readStreamToString(conn.getInputStream(), "UTF-8");
//
//            //выводим информацию в консоль
//            System.out.println("URL:" + url);
//            System.out.println("Html:\n" + html);
//        } catch (IOException ex) {
//            Logger.getLogger(YandexFotkiBackup.class.getName()).log(Level.SEVERE, null, ex);
//        }


        ReadXMLDownloadHendler hendler = new ReadXMLDownloadHendler();
        //parseNextPage(url, hendler);
        hendler.setLinkNes(url);
        String urlNext;
        while ((urlNext = hendler.getLinkNes()) != null) {
            hendler = new ReadXMLDownloadHendler();
            parseNextPage(urlNext, hendler);
            List<PhotoInfo> downloadList = hendler.getCollectionAlboms();
            ObservableList<GuiAlbomsData> d = tableView.getItems();
            for (int i = 0; i < d.size(); i++) {
                if (d.get(i).getAlbomInfo() == albom) {
                    d.get(i).setProgressDownload(0);
                    DownloaderThread downloaderThread = new DownloaderThread(albom, downloadList, d.get(i));
                    downloaderThread.start();
                    threadManager.addThread(albom, downloaderThread);
                }
            }
        }

    }

    @Override
    public void onUserNameUpdated() {
        //root.getChildren().add(tableView);
        //устанавливаем соединение
        //URLConnection conn = new URL("http://api-fotki.yandex.ru/api/users/norom/albums/published/").openConnection();

        //читаем то, что отдал нам сервер
        //String html = readStreamToString(conn.getInputStream(), "UTF-8");

        //выводим информацию в консоль
        //System.out.println("URL:" + url);
        //System.out.println("Html:\n" + html);

        ReadXMLAllAlbomsHendler hendler = new ReadXMLAllAlbomsHendler();
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();
            String url = "http://api-fotki.yandex.ru/api/users/" + userName + "/albums/";
            try {
                saxParser.parse(url, hendler);
            } catch (SAXException | IOException ex) {
                Logger.getLogger(YandexFotkiBackup.class.getName()).log(Level.SEVERE, null, ex);
                //TODO show window with error name
            }
        } catch (Exception e) {
            Logger.getLogger(YandexFotkiBackup.class.getName()).log(Level.SEVERE, null, e);
        }
        ObservableList<GuiAlbomsData> data = FXCollections.observableArrayList();
        for (AlbomInfo info : hendler.getCollectionAlboms()) {
            data.add(new GuiAlbomsData(this, info));
            tableView.setItems(data);
        }
    }

    private TableView getTableView() {
        TableView tableViewLocal = new TableView();

        tableViewLocal.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        TableColumn firstNameCol = new TableColumn();
        firstNameCol.setText("АйДи Альбома");
        firstNameCol.setCellValueFactory(new PropertyValueFactory("idAlbom"));
        TableColumn lastNameCol = new TableColumn();
        lastNameCol.setText("Название Альбома");
        lastNameCol.setCellValueFactory(new PropertyValueFactory("nameAlbom"));
        lastNameCol.setEditable(true);
        final Callback<TableColumn, TableCell> cellFactory =
                new Callback<TableColumn, TableCell>() {
                    @Override
                    public TableCell call(TableColumn p) {
                        return new EditingCell();
                    }
                };
        lastNameCol.setCellFactory(cellFactory);
        TableColumn countPhotoNameCol = new TableColumn();
        countPhotoNameCol.setText("Число фоток");
        countPhotoNameCol.setCellValueFactory(new PropertyValueFactory("countPhoto"));
        TableColumn progressCol = new TableColumn();
        progressCol.setText("Загрузка");
        progressCol.setCellValueFactory(new PropertyValueFactory("progressDownload"));
        progressCol.setCellFactory(ProgressBarTableCell.forTableColumn());
        tableViewLocal.getColumns().addAll(firstNameCol, lastNameCol, countPhotoNameCol, progressCol);
        return tableViewLocal;
    }

    private String readStreamToString(InputStream in, String encoding)
            throws IOException {
        StringBuilder b = new StringBuilder();
        InputStreamReader r = new InputStreamReader(in, encoding);
        int c;
        while ((c = r.read()) != -1) {
            b.append((char) c);
        }
        return b.toString();
    }

    /**
     * The main() method is ignored in correctly deployed JavaFX application.
     * main() serves only as fallback in case the application can not be
     * launched through deployment artifacts, e.g., in IDEs with limited FX
     * support. NetBeans ignores main().
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

    private void parseNextPage(String url, ReadXMLDownloadHendler hendler) {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();

            try {
                saxParser.parse(url, hendler);
            } catch (SAXException | IOException ex) {
                Logger.getLogger(YandexFotkiBackup.class.getName()).log(Level.SEVERE, null, ex);
                //TODO show window with error name
            }
        } catch (Exception e) {
            Logger.getLogger(YandexFotkiBackup.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    boolean userLogging(String text, String text0) {
        BorderPane root = new BorderPane();
        Scene scene = new Scene(root, 800, 600);
        scene.getStylesheets().add("yandexfotkibackup/table.css");
        stage.setScene(scene);
        stage.sizeToScene();
        tableView = getTableView();
        root.setCenter(tableView);
        final ImageView imageViewPause = new ImageView("yandexfotkibackup/res/Pause_35.png");
        ImageView imageViewPlay = new ImageView("yandexfotkibackup/res/Play_25.png");
        imageViewPlay.resize(30, 30);
        imageViewPause.resize(30, 30);
        Button buttonPlay = new Button("", imageViewPlay);
        EventHandler<ActionEvent> handler = new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {
                threadManager.resumeAllThread();
            }
        };
        buttonPlay.setOnAction(handler);
        Button buttonPause = new Button("", imageViewPause);
        handler = new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {
                threadManager.pauseAllThread();
            }
        };
        buttonPause.setOnAction(handler);
        ToolBar toolBar = new ToolBar(
                buttonPause,
                buttonPlay);
        root.setTop(toolBar);
        setUserName(text);
        onUserNameUpdated();
        return false;

    }

    private void goToLogin() {
        try {
            LoginController lc = (LoginController) replaceSceneContent("YaLogin.fxml");
            lc.setApp(this);
        } catch (Exception ex) {
            Logger.getLogger(YandexFotkiBackup.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static class EventHandlerImpl implements EventHandler<ActionEvent> {

        private final TextField tb;
        private final YandexFotkiBackup mainClass;

        public EventHandlerImpl(TextField tb, YandexFotkiBackup mainClass) {
            this.tb = tb;
            this.mainClass = mainClass;
        }

        @Override
        public void handle(ActionEvent event) {
            String text = tb.getText();
            mainClass.setUserName(text);
            System.out.println("Find user name: " + text);
            mainClass.onUserNameUpdated();
        }
    }

    private static class EventHandlerImplCell implements EventHandler<CellEditEvent<GuiAlbomsData, Boolean>> {

        YandexFotkiBackup mainClass;

        public EventHandlerImplCell(YandexFotkiBackup mainClass) {
            this.mainClass = mainClass;
        }

        @Override
        public void handle(CellEditEvent<GuiAlbomsData, Boolean> t) {
            System.out.println("Commit");
        }
    }

    private Initializable replaceSceneContent(String fxml) throws Exception {
        FXMLLoader loader = new FXMLLoader();
        InputStream in = YandexFotkiBackup.class.getResourceAsStream(fxml);
        loader.setBuilderFactory(new JavaFXBuilderFactory());
        loader.setLocation(YandexFotkiBackup.class.getResource(fxml));
        AnchorPane page;
        try {
            page = (AnchorPane) loader.load(in);
        } finally {
            in.close();
        }
        Scene scene = new Scene(page, 800, 600);
        stage.setScene(scene);
        stage.sizeToScene();
        return (Initializable) loader.getController();
    }
}
